// Lead Source Type
var _TYPE_INTERNET = '2';
var _TYPE_INBOUNDCALL = '33';
var _TYPE_WEBFORM = '34';
var _TYPE_IMPORT = '35';
var _TYPE_OTHER = '64';

var selectTag = $('#Type');

// For view Create
var createLeadSourceForm = document.getElementById("CreateLeadSourceForm");
if (createLeadSourceForm != undefined && createLeadSourceForm != null) {
	// Create new model to apply to view
    var createModel = new function () {

        this.Title = ko.observable('')
			.extend({ maxLength: 200 })
			.extend({ required: { message: "Title is required"} })
			.extend({ pattern: { message: 'This field cannot contain special characters.', params: '^([a-zA-Z0-9\\s\\-\\_]+)*$'} });
        this.SourceCost = ko.observable();
        this.SourceCostHidden = ko.computed(function () { return this.SourceCost(); }, this)
			.extend({ maxLength: 10 })
            .extend({
                validation: {
                    validator: function (val) {
                        if (val != undefined && val != '') {
                            // Check is decimal
                            return !isNaN(parseFloat(val)) && isFinite(val);
                        }
                        return true;
                    },
                    message: 'Expected Cost must be a number or blank.'
                }
            })
            .extend({
                validation: {
                    validator: function (val) {
                        if (val != undefined && val != '' && parseFloat(val) > 214748) {
                            return false;
                        }
                        return true;
                    },
                    message: 'Expected Cost must be less than or equal to 214748'
                }
            })
			.extend({ pattern: { message: 'Expected Cost must be a number or blank.', params: '^[0-9 .]*$'} });

        this.TypeOptions = ko.observableArray(data.TypeList);
        this.Type = ko.observable('').extend({ required: { message: "Type is required"} });

        this.LeadSellerOptions = ko.observableArray(data.LeadSellerList);
        this.LeadSeller = ko.observable();

        this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
        this.InboundPhone = ko.observable();

        this.EmailAddress = ko.observable();

        this.IsEmptyType = ko.computed(function () {
            if (this.Type() != undefined && this.Type() != '') {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasWebformType = ko.computed(function () {
            //            if (this.Type() == _TYPE_WEBFORM) {
            //                return true;
            //            }
            //            else {
            return false;
            //            }
        }, this);

        this.HasWebformTypeMessage = ko.computed(function () {
            if (this.Type() == _TYPE_WEBFORM) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasInternetType = ko.computed(function () {
            //            if (this.Type() == _TYPE_INTERNET) {
            //                return true;
            //            }
            //            else 
            //            {
            return false;
            //            }
        }, this);

        this.HasInternetTypeSeller = ko.computed(function () {
            if (this.Type() == _TYPE_INTERNET) {
                return true;
            }
            else {
                return false;
            }
        }, this);



        this.HasInboundCallType = ko.computed(function () {
            if (this.Type() == _TYPE_INBOUNDCALL) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        //----------------------------------------Handle Send Email---------------------------------------/
        //
        this.HasSendMail = ko.computed(function () {
            if (this.Type() == _TYPE_WEBFORM) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasSendMailButton = ko.computed(function () {
            return false;

        }, this);

        this.EmailAddress = ko.observable();
        this.ValidateSendMail = ko.computed(function () {
            var addresses = this.EmailAddress();
            if (addresses != undefined && addresses != null && addresses != '') {
                addresses = addresses.replace(new RegExp(';', 'g'), ',');
                var addressList = addresses.split(',');

                if (validateListEmail(addressList)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                return false;
            }
        }, this);

        this.InvalidEmail = ko.computed(function () {
            if (this.EmailAddress() != null && this.EmailAddress() != '' && this.ValidateSendMail() == false) {
                return true;
            }
            else {
                return false;
            }

        }, this);

        this.ErrorEmailMessage = ko.observable();

        this.ShowErrorEmailMessage = ko.computed(function () {
            if (this.ErrorEmailMessage() != null && this.ErrorEmailMessage() != '' && this.ValidateSendMail() == false) {
                return true;
            }
            else {
                return false;
            }

        }, this);


        this.SendEmail = function () {
            if (createModel.ValidateSendMail()) {
                var data = { "mailTo": createModel.EmailAddress() };

                openProcess();
                $.post("/LeadSource/SendMail", data, function (result) {

                    hideProcess();

                    if (result.Message != undefined && result.Message != null && result.Message != '') {
                        // Error while processing
                        createModel.ValidateSendMail(false);
                        createModel.ErrorEmailMessage('An error occurred while sending email.');

                        return false;
                    }
                    else {
                        // Show complete send mail
                        createModel.ErrorEmailMessage("");
                        init_popupSendMail();

                        return false;
                    }
                });
            }
            else {
                if (createModel.InvalidEmail()) {
                    createModel.ErrorEmailMessage("Enter a valid email.");
                }
                return false;
            }
        };

        //-----------------------Handle Provision Dial-IQ Inbound Phone---------------------------------------/
        //

        // Show Provision button & Hide Provision pane
        this.HasProvisionDialIQ = ko.observable(false);
        this.DialIQType = ko.observable();

        this.ShowProvisionDialIQ = ko.computed(function () {
            if (this.HasInboundCallType() && this.HasProvisionDialIQ()) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.ShowLocalPane = ko.computed(function () {
            if (this.DialIQType() == 'local') {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.ShowLocalDialIQButton = ko.observable(true);
        this.ShowLocalDialIQResult = ko.observable(false);
        this.LocalDialIQResult = ko.observable();
        this.ActiveLocalGetNumber = ko.observable(false);
        this.ErrorGetNumberLocal = ko.observable();
        this.ShowErrorGetNumberLocal = ko.observable(false);
        this.ShowTollfreeDialIQButton = ko.observable(true);
        this.ShowTollfreeDialIQResult = ko.observable(false);
        this.TollfreeDialIQResult = ko.observable();
        this.msgInboundNumberLimited = ko.observable('');
        this.InboundNumberCountLimited = ko.observable(data.InboundNumberCountLimited);

        if (this.InboundNumberCountLimited() <= 0) {
            this.msgInboundNumberLimited(data.InboundNumberLimitAlert);
        }

        this.ProvisionDialIQ = function () {
            if (createModel.InboundNumberCountLimited() > 0) {
                createModel.HasProvisionDialIQ(true);
                $("#btnProvisionDialIQ").removeClass("btn-provision");
                $("#btnProvisionDialIQ").addClass("btn-provision-disabled");
            }
            else {
                if (!($("#btnProvisionDialIQ").hasClass("btn-provision-disabled"))) {
                    showmsgError();
                }
            }

            return false;
        };

        this.GetNumberTollfreeType = function () {
            if (createModel.InboundNumberCountLimited() > 0) {
                var data = {};

                openProcess();

                $.post("/LeadSource/GetTollFreePhone", data, function (result) {

                    hideProcess();

                    if (result.ErrorCode == '1') {
                        // Error process
                        createModel.ShowTollfreeDialIQResult(false);
                        createModel.ShowTollfreeDialIQButton(true);

                        createModel.ShowErrorGetNumberLocal(true);
                        createModel.ErrorGetNumberLocal(result.Message);

                        return false;
                    }
                    else {
                        // Show complete
                        createModel.ShowTollfreeDialIQResult(true);
                        createModel.ShowTollfreeDialIQButton(false);

                        createModel.ShowErrorGetNumberLocal(false);
                        createModel.ErrorGetNumberLocal('');

                        createModel.TollfreeDialIQResult(result.Message);


                        //Refresh this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
                        createModel.InboundPhoneOptions(result.InboundPhoneList);
                        createModel.InboundPhone(result.Message);

                        // Remove old div tags
                        var tempEl = document.getElementById("InboundPhone");
                        if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                        jcf.customForms.replaceElement("InboundPhone");
                        // Must be executed after knockout rendering
                        setTimeout("jcf.customForms.replaceElement('InboundPhone')", 0);

                        if (result.InboundNumberCountLimited <= 0) {
                            createModel.msgInboundNumberLimited(result.InboundNumberLimitAlert);
                            createModel.InboundNumberCountLimited(result.InboundNumberCountLimited);
                        }

                        return false;
                    }
                });
            }
            else {
                showmsgError();
            }

            return false;
        };

        this.GetNumberLocalType = function () {
            if (createModel.ActiveLocalGetNumber()) {
                if (createModel.InboundNumberCountLimited() > 0) {
                    var data = { "areaCode": $("#AreaCodeInput").val() };

                    openProcess();
                    $.post("/LeadSource/GetInboundPhone", data, function (result) {

                        hideProcess();

                        if (result.ErrorCode == '1') {
                            // Error process
                            createModel.ShowLocalDialIQResult(false);
                            createModel.ShowLocalDialIQButton(true);

                            createModel.ShowErrorGetNumberLocal(true);
                            createModel.ErrorGetNumberLocal(result.Message);

                            return false;
                        }
                        else {
                            // Show complete
                            createModel.ShowLocalDialIQResult(true);
                            createModel.ShowLocalDialIQButton(false);

                            createModel.ShowErrorGetNumberLocal(false);
                            createModel.ErrorGetNumberLocal('');

                            createModel.LocalDialIQResult(result.Message);

                            //Refresh this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
                            createModel.InboundPhoneOptions(result.InboundPhoneList);
                            createModel.InboundPhone(result.Message);

                            // Remove old div tags
                            var tempEl = document.getElementById("InboundPhone");
                            if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                            jcf.customForms.replaceElement("InboundPhone");
                            // Must be executed after knockout rendering
                            setTimeout("jcf.customForms.replaceElement('InboundPhone')", 0);

                            if (result.InboundNumberCountLimited <= 0) {
                                createModel.msgInboundNumberLimited(result.InboundNumberLimitAlert);
                                createModel.InboundNumberCountLimited(result.InboundNumberCountLimited);
                            }

                            return false;
                        }
                    });
                }
                else {
                    showmsgError();
                }
            }
            return false;
        };

        //-----------------------Add new Lead Source---------------------------------------/
        this.createLeadSource = function () {
            if ($("#Title").val() == '') {
                this.Title('');
            }
            if ($("#Type").val() == '') {
                this.Type('');
            }
            if ($("#LeadSeller option:selected").val() == '' || this.HasInternetType == false) {
                this.LeadSeller('');
            }
            if ($("#InboundPhone option:selected").val() == '' || this.HasInboundCallType == false) {
                this.InboundPhone('');
            }
            if ($("#SourceCost").val() == '') {
                this.SourceCost('');
            }

            if ($("#EmailAddress").val() == '') {
                this.EmailAddress('');
            }

            if (createModel.errors().length == 0) {
                // start process

                // Write an ajax function to post userinfo to server
                // Using jquery json post
                var data = {
                    "Title": this.Title(),
                    "Type": this.Type(),
                    "LeadSellerId": this.LeadSeller(),
                    "InboundPhone": this.InboundPhone(),
                    "SourceCost": this.SourceCost(),
                    "EmailAddress": this.EmailAddress()
                };

                openProcess();
                $.post("/LeadSource/Create", data, function (result) {

                    hideProcess();

                    if (result.ErrorCode == 1296) {
                        //Title is existed
                        $("#rowTitle").each(function (index, value) {
                            $(this).find("span").removeAttr("style");
                            $(this).find("span").attr("style", "").text("This title already exists.");

                            $(this).find("#Title").removeAttr("class");
                            $(this).find("#Title").attr("class", "text error");
                        });
                    }
                    else if (result.ErrorCode == 1) {
                        $("#rowSourceCost").each(function (index, value) {
                            $(this).find("span").removeAttr("style");
                            $(this).find("span").attr("style", "").text("Lead Source Cost must be a number or blank.");

                            $(this).find("#SourceCost").removeAttr("class");
                            $(this).find("#SourceCost").attr("class", "text error");
                        });
                    }
                    else if (result.Message != undefined && result.Message != null && result.Message != "") {
                        showmsgErrorNetwork();
                    }
                    else {
                        window.location.href = "/LeadSource";
                    }
                    // End process
                });

                return true;
            }
            else {
                //this.validateForm(createModel.errors().length > 0);
                createModel.errors.showAllMessages();
                if (!createModel.IsEmptyType()) {
                    selectTag.parent().children('.select-select').addClass('select-error-margintop20');
                }
                return false;
            }
        };

    };
	createModel.errors = ko.validation.group(createModel);
	ko.applyBindings(createModel, document.getElementById("CreateLeadSourceForm"));
}

// For view edit
var updateLeadSourceForm = document.getElementById("UpdateLeadSourceForm");
if (updateLeadSourceForm != undefined && updateLeadSourceForm != null) {
	// Create new model to apply to view
    var updateModel = new function () {
        this.LeadSourceId = ko.observable(data.LeadSourceItem.LeadSourceId);

        this.Title = ko.observable(data.LeadSourceItem.Title)
			.extend({ maxLength: 200 })
			.extend({ required: { message: "Title is required"} })
			.extend({ pattern: { message: 'This field cannot contain special characters.', params: '^([a-zA-Z0-9\\s\\-\\_]+)*$'} });
        this.SourceCost = ko.observable(data.LeadSourceItem.SourceCost);
        this.SourceCostHidden = ko.computed(function () { return this.SourceCost(); }, this)
			.extend({ maxLength: 10 })
            .extend({
                validation: {
                    validator: function (val) {
                        if (val != undefined && val != '') {
                            // Check is decimal
                            return !isNaN(parseFloat(val)) && isFinite(val);
                        }
                        return true;
                    },
                    message: 'Expected Cost must be a number or blank.'
                }
            })
            .extend({
                validation: {
                    validator: function (val) {
                        if (val != undefined && val != '' && parseFloat(val) > 214748) {
                            return false;
                        }
                        return true;
                    },
                    message: 'Expected Cost must be less than or equal to 214748'
                }
            })
			.extend({ pattern: { message: 'Lead Source Cost must be a number or blank.', params: '^[0-9 .]*$'} });

        this.TypeOptions = ko.observableArray(data.TypeList);
        this.Type = ko.observable(data.LeadSourceItem.Type).extend({ required: { message: "Type is required"} });

        this.LeadSellerOptions = ko.observableArray(data.LeadSellerList);
        this.LeadSeller = ko.observable(data.LeadSourceItem.LeadSeller);

        this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
        if (data.LeadSourceItem.InboundPhone == '') {
            this.InboundPhone = ko.observable();
        }
        else {
            this.InboundPhone = ko.observable(data.LeadSourceItem.InboundPhone);
        }

        this.EmailAddress = ko.observable();
        this.IsEmptyType = ko.computed(function () {
            if (this.Type() != undefined && this.Type() != '') {

                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasWebformType = ko.computed(function () {
            //            if (this.Type() == _TYPE_WEBFORM) {
            //                return true;
            //            }
            //            else {
            return false;
            //            }
        }, this);

        this.HasWebformTypeMessage = ko.computed(function () {
            if (this.Type() == _TYPE_WEBFORM) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasInternetType = ko.computed(function () {
            //            if (this.Type() == _TYPE_INTERNET) {
            //                return true;
            //            }
            //            else {
            return false;
            //            }
        }, this);

        this.HasInternetTypeSeller = ko.computed(function () {
            if (this.Type() == _TYPE_INTERNET) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasInboundCallType = ko.computed(function () {
            if (this.Type() == _TYPE_INBOUNDCALL) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        //----------------------------------------Handle Send Email---------------------------------------/
        //
        this.HasSendMail = ko.computed(function () {
            if (this.Type() == _TYPE_WEBFORM) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.HasSendMailButton = ko.computed(function () {
            return false;

        }, this);

        this.EmailAddress = ko.observable();
        this.ValidateSendMail = ko.computed(function () {
            var addresses = this.EmailAddress();
            if (addresses != undefined && addresses != null && addresses != '') {
                addresses = addresses.replace(new RegExp(';', 'g'), ',');
                var addressList = addresses.split(',');

                if (validateListEmail(addressList)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                return false;
            }
        }, this);

        this.InvalidEmail = ko.computed(function () {
            if (this.EmailAddress() != null && this.EmailAddress() != '' && this.ValidateSendMail() == false) {
                return true;
            }
            else {
                return false;
            }

        }, this);

        this.ErrorEmailMessage = ko.observable();

        this.ShowErrorEmailMessage = ko.computed(function () {
            if (this.ErrorEmailMessage() != null && this.ErrorEmailMessage() != '' && this.ValidateSendMail() == false) {
                return true;
            }
            else {
                return false;
            }

        }, this);


        this.SendEmail = function () {
            if (updateModel.ValidateSendMail()) {
                var data = { "mailTo": updateModel.EmailAddress() };

                openProcess();

                $.post("/LeadSource/SendMail", data, function (result) {
                    hideProcess();

                    if (result.Message != undefined && result.Message != null && result.Message != '') {
                        // Error while processing
                        updateModel.ValidateSendMail(false);
                        updateModel.ErrorEmailMessage('An error occurred while sending email.');

                        return false;
                    }
                    else {
                        // Show complete send mail
                        updateModel.ErrorEmailMessage("");
                        init_popupSendMail();

                        return false;
                    }
                });
            }
            else {
                if (updateModel.InvalidEmail()) {
                    updateModel.ErrorEmailMessage("Enter a valid email.");
                }
                return false;
            }
        };

        //-----------------------Handle Provision Dial-IQ Inbound Phone---------------------------------------/
        //

        // Show Provision button & Hide Provision pane
        this.HasProvisionDialIQ = ko.observable(false);
        this.DialIQType = ko.observable();

        this.ShowProvisionDialIQ = ko.computed(function () {
            if (this.HasInboundCallType() && this.HasProvisionDialIQ()) {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.ShowLocalPane = ko.computed(function () {
            if (this.DialIQType() == 'local') {
                return true;
            }
            else {
                return false;
            }
        }, this);

        this.ShowLocalDialIQButton = ko.observable(true);
        this.ShowLocalDialIQResult = ko.observable(false);
        this.LocalDialIQResult = ko.observable();
        this.ActiveLocalGetNumber = ko.observable(false);
        this.ErrorGetNumberLocal = ko.observable();
        this.ShowErrorGetNumberLocal = ko.observable(false);
        this.ShowTollfreeDialIQButton = ko.observable(true);
        this.ShowTollfreeDialIQResult = ko.observable(false);
        this.TollfreeDialIQResult = ko.observable();
        this.msgInboundNumberLimited = ko.observable('');
        this.InboundNumberCountLimited = ko.observable(data.InboundNumberCountLimited);

        if (this.InboundNumberCountLimited() <= 0) {
            this.msgInboundNumberLimited(data.InboundNumberLimitAlert);
        }

        this.ProvisionDialIQ = function () {
            if (updateModel.InboundNumberCountLimited() > 0) {
                updateModel.HasProvisionDialIQ(true);
                $("#btnProvisionDialIQ").removeClass("btn-provision");
                $("#btnProvisionDialIQ").addClass("btn-provision-disabled");
            }
            else {
                if (!($("#btnProvisionDialIQ").hasClass("btn-provision-disabled"))) {
                    showmsgError();
                }
            }

            return false;
        };

        this.GetNumberTollfreeType = function () {
            if (createModel.InboundNumberCountLimited() > 0) {
                var data = {};

                openProcess();
                $.post("/LeadSource/GetTollFreePhone", data, function (result) {

                    hideProcess();
                    if (result.ErrorCode == '1') {
                        // Error process
                        updateModel.ShowTollfreeDialIQResult(false);
                        updateModel.ShowTollfreeDialIQButton(true);

                        updateModel.ShowErrorGetNumberLocal(true);
                        updateModel.ErrorGetNumberLocal(result.Message);

                        return false;
                    }
                    else {
                        // Show complete
                        updateModel.ShowTollfreeDialIQResult(true);
                        updateModel.ShowTollfreeDialIQButton(false);

                        updateModel.ShowErrorGetNumberLocal(false);
                        updateModel.ErrorGetNumberLocal('');

                        updateModel.TollfreeDialIQResult(result.Message);

                        // Refresh this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
                        updateModel.InboundPhoneOptions(result.InboundPhoneList);
                        updateModel.InboundPhone(result.Message);

                        // Remove old div tags
                        var tempEl = document.getElementById("InboundPhone");
                        if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                        jcf.customForms.replaceElement("InboundPhone");
                        // Must be executed after knockout rendering
                        setTimeout("jcf.customForms.replaceElement('InboundPhone')", 0);

                        return false;
                    }
                });
            }
            else {
                showmsgError();
            }

            return false;
        };

        this.GetNumberLocalType = function () {
            if (updateModel.ActiveLocalGetNumber()) {
                if (createModel.InboundNumberCountLimited() > 0) {
                    var data = { "areaCode": $("#AreaCodeInput").val() };

                    openProcess();
                    $.post("/LeadSource/GetInboundPhone", data, function (result) {

                        hideProcess();
                        if (result.ErrorCode == '1') {
                            // Error process
                            updateModel.ShowLocalDialIQResult(false);
                            updateModel.ShowLocalDialIQButton(true);

                            updateModel.ShowErrorGetNumberLocal(true);
                            updateModel.ErrorGetNumberLocal(result.Message);

                            return false;
                        }
                        else {
                            // Show complete
                            updateModel.ShowLocalDialIQResult(true);
                            updateModel.ShowLocalDialIQButton(false);

                            updateModel.ShowErrorGetNumberLocal(false);
                            updateModel.ErrorGetNumberLocal('');

                            updateModel.LocalDialIQResult(result.Message);

                            //Refresh this.InboundPhoneOptions = ko.observableArray(data.InboundPhoneList);
                            updateModel.InboundPhoneOptions(result.InboundPhoneList);
                            updateModel.InboundPhone(result.Message);

                            // Remove old div tags
                            var tempEl = document.getElementById("InboundPhone");
                            if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                            jcf.customForms.replaceElement("InboundPhone");
                            // Must be executed after knockout rendering
                            setTimeout("jcf.customForms.replaceElement('InboundPhone')", 0);

                            return false;
                        }
                    });
                }
                else {
                    showmsgError();
                }
            }
            return false;
        };

        //-----------------------Update Lead Source---------------------------------------/
        this.updateLeadSource = function () {
            if ($("#Title").val() == '') {
                this.Title('');
            }
            if ($("#InboundPhone option:selected").val() == '' || this.HasInboundCallType == false) {
                this.InboundPhone('');
            }
            else {
                this.InboundPhone($("#InboundPhone option:selected").val());
            }
            if ($("#SourceCost").val() == '') {
                this.SourceCost('');
            }
            if ($("#EmailAddress").val() == '') {
                this.EmailAddress('');
            }

            if (updateModel.errors().length == 0) {

                // start process

                // Write an ajax function to post userinfo to server
                // Using jquery json post
                var data = {
                    "LeadSourceId": updateModel.LeadSourceId(),
                    "Title": updateModel.Title(),
                    "InboundPhone": updateModel.InboundPhone(),
                    "SourceCost": updateModel.SourceCost(),
                    "EmailAddress": updateModel.EmailAddress()
                };

                openProcess();
                $.post("/LeadSource/Edit", data, function (result) {

                    hideProcess();

                    if (result.ErrorCode == 1296) {
                        //Title is existed
                        $("#rowTitle").each(function (index, value) {
                            $(this).find("span").removeAttr("style");
                            $(this).find("span").attr("style", "").text("This title already exists.");

                            $(this).find("#Title").removeAttr("class");
                            $(this).find("#Title").attr("class", "text error");
                        });
                    }
                    else if (result.ErrorCode == 1) {
                        $("#rowSourceCost").each(function (index, value) {
                            $(this).find("span").removeAttr("style");
                            $(this).find("span").attr("style", "").text("Lead Source Cost must be a number or blank.");

                            $(this).find("#SourceCost").removeAttr("class");
                            $(this).find("#SourceCost").attr("class", "text error");
                        });
                    }
                    else if (result.Message != undefined && result.Message != null && result.Message != "") {
                        showmsgErrorNetwork();
                    }
                    else {
                        window.location.href = "/LeadSource";
                    }
                    // end process
                });

                return true;
            }
            else {
                //this.validateForm(updateModel.errors().length > 0);
                updateModel.errors.showAllMessages();
                return false;
            }
        };

    };
	updateModel.errors = ko.validation.group(updateModel);
	ko.applyBindings(updateModel, document.getElementById("UpdateLeadSourceForm"));
}

function validateListEmail(emailSendList) 
{
	var emailRegular = new RegExp("^([\\w]+(?:\\.[\\w]+)*)@((?:[\\w]+\\.)*\\w[\\w]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$");
	var validateResult = false;
	for (var i = 0; i < emailSendList.length; i++) {
		if (emailSendList[i] && $.trim(emailSendList[i]) != "") {
			if (emailRegular.test($.trim(emailSendList[i]))) {
				validateResult = true;
			}
			else {
				return false;
			}
		}
	}

	return validateResult;
}

function init_popupSendMail() {
    $.fancybox($('#popup-SendMail'), 
    {
		padding: 0,
		closeBtn: false,
		helpers: {
			overlay: {
				opacity: 0.8,
				css: { 'background-color': '#11619D' }
			}
		}
      });
    $('#fancybox-overlay').css("display", "block");
    $('#fancybox-overlay').css("opacity", "0.8");
    $('#fancybox-overlay').css("background-color", "#11619D");
}

function getNumberKeyUp(evt) {
	var areaCodeInput = $("#AreaCodeInput").val();

	if ((areaCodeInput.length == 3) && (validateAreaCode(areaCodeInput))) {
		if (createLeadSourceForm != undefined && createLeadSourceForm != null) {
			createModel.ActiveLocalGetNumber(true);
		}
		if (updateLeadSourceForm != undefined && updateLeadSourceForm != null) {
			updateModel.ActiveLocalGetNumber(true);
		}

		$("#LocalDialIQButton").removeClass("btn-getnumber-gray");
		$("#LocalDialIQButton").addClass("btn-getnumber-blue");
	}
	else {
		if (createLeadSourceForm != undefined && createLeadSourceForm != null) {
			createModel.ActiveLocalGetNumber(false);
		}
		if (updateLeadSourceForm != undefined && updateLeadSourceForm != null) {
			updateModel.ActiveLocalGetNumber(false);
		}
		$("#LocalDialIQButton").removeClass("btn-getnumber-blue");
		$("#LocalDialIQButton").addClass("btn-getnumber-gray");
	}
}

function validateAreaCode(areaCode) {
	var areaCodeRegular = new RegExp(PARAM_AREA_CODE);

	if (areaCodeRegular.test(areaCode))
		return true;

	return false;
}

function validateInboundPhone(phone) {
	var phoneInboundRegular = new RegExp(PARAM_INBOUND_PHONE);
	if (phoneInboundRegular.test(phone))
		return true;

	return false;
}

function showmsgError() {
    $('#fancybox-overlay').show();
    $('#popupError').showPopup({
        width: 500
    });
}

function showmsgErrorNetwork() {
    $('#fancybox-overlay').show();
    $('#popupErrorNetwork').showPopup({
        width: 500
    });
}

$(document).ready(function () {

	// Set value of EmailAddress input when EmailAddress occur change event
	$('#EmailAddress').change(function() {

		if (createLeadSourceForm != undefined && createLeadSourceForm != null) {
			if (createModel.ValidateSendMail()) {
				createModel.ErrorEmailMessage("");
			}
			else {
				if (createModel.InvalidEmail()) {
					createModel.ErrorEmailMessage("Enter a valid email.");
				}
				else {
					createModel.ErrorEmailMessage("");
				}
			}
		}
		if (updateLeadSourceForm != undefined && updateLeadSourceForm != null) {
			if (updateModel.ValidateSendMail()) {
				updateModel.ErrorEmailMessage("");
			}
			else {
				if (updateModel.InvalidEmail()) {
					updateModel.ErrorEmailMessage("Enter a valid email.");
				}
				else {
					updateModel.ErrorEmailMessage("");
				}
			}
		}
	});

	// Set value of Type Select when Type occur change event
	$('#Type').change(function() {
		if (createLeadSourceForm != undefined && createLeadSourceForm != null) {
			createModel.EmailAddress("");
			createModel.ErrorEmailMessage("");
		}
		if (updateLeadSourceForm != undefined && updateLeadSourceForm != null) {
			updateModel.EmailAddress("");
			updateModel.ErrorEmailMessage("");
		}
	});


	// Fix case: show error message of dropdown
	selectTag.change(function () {
		if (selectTag.hasClass('error')) {
			selectTag.parent().children('.select-select').addClass('select-error-margintop20');
		}
		else {
			selectTag.parent().children('.select-select').removeClass('select-error-margintop20');
		}
	});

	// Fix width of dropdown
	$('#rowLeadSeller').find('.select-area').attr('style', 'width:425px');
	// Fix height of dropdown: set height = 200px if height > 200px
	$('.drop-list').each(function (i, e) {
		if ($(e).height() > 200) {
			$(e).attr('style', 'height: 200px; overflow-x: hidden; overflow-y: auto;');
		}
	});
});
